package com.javabasic.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author xiongmin
 * @ClassName 拼写单词
 * @Description TODO
 * @Date 2019/8/18 11:33
 * @Version 1.0
 **/
public class 拼写单词 {


    public int countCharacters(String[] words, String chars) {
        Map<Character,Integer> charsMap = getMap(chars);
        int result = 0;
        Map<Character,Integer> wordMap = null;
        Set<Character> set = null;
        for (String str :
                words) {
            wordMap = getMap(str);
            set = wordMap.keySet();
            boolean flag = true;
            for (Character ch :
                    set) {
                if (!charsMap.containsKey(ch)) {
                    flag = false;
                    break;
                }
                if (wordMap.get(ch) > charsMap.get(ch)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                result += str.length();
            }
        }
        return  result;
    }

    public Map getMap(String str) {
        HashMap<Character,Integer> result = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            if (result.containsKey(str.charAt(i))) {
                result.put(str.charAt(i),result.get(str.charAt(i))+1);
            } else {
                result.put(str.charAt(i),1);
            }
        }
        return result;
    }
}
